using System;
using ECommerce.Library.Mail;
using Entity;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using eShop.Model;


namespace eShop.Business
{
    public class Email
    {
        private const string _invoiceEmailTemplateFilePath = "~/templates/invoice-email-template.txt";
        private const string _passwordRecoveryEmailTemplateFilePath = "~/templates/password-recovery-template.txt";
        private const string _registrationEmailTemplateFilePath = "~/templates/registration-template.txt";
        private const string _registrationEmailAdminTemplateFilePath = "~/templates/registration-template-admin.txt";
        private const string _stockAlertEmailAdminTemplateFilePath = "~/templates/stock-alert-email-admin.txt";
        private const string _inqueryEmailAdminTemplateFilePath = "~/templates/inquery-email-admin.txt";

        #region _ACTIVE_FUNCTION

        public string GetTemplate(string _templatePath)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(_templatePath)))
            {
                StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_templatePath));
                string templateContent = reader.ReadToEnd();
                reader.Close();
                return templateContent;
            }
            else
            {
                return string.Empty;
            }
        }

        public bool SendGenericEmail(string toName, string toEmail, string subject, string body)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailText = body;
                string mailSubject = SiteSettings.CompanyName + " : " + subject;
                NameValueCollection items = new NameValueCollection();

                items.Add("ReceiverName", toName);
                items.Add("ReceiverEmail", toEmail);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                //Emailer.SendMail(toEmail, SiteSettings.AdminEmail, SiteSettings.CompanyName, subject, body);
                return true;
            }
            catch { return false; }
        }

        public bool SendRegistrationEmail(User user)
        {
            MailSettings mailSettings = new MailSettings();
            mailSettings.ServerAddress = SiteSettings.EmailServer;
            mailSettings.Port = SiteSettings.EmailPort;
            mailSettings.UserName = SiteSettings.EmailUserName;
            mailSettings.Password = SiteSettings.EmailPassword;
            mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
            mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
            mailSettings.SenderName = SiteSettings.CompanyName;
            string mailText = string.Empty;
            string mailSubject = SiteSettings.CompanyName + " :  New  Registration";
            mailText = GetTemplate(_registrationEmailTemplateFilePath);
            if (!string.IsNullOrEmpty(mailText))
            {
                mailText = mailText.Replace("<##FirstName##>", user.Profile.FirstName);
                mailText = mailText.Replace("<##LastName##>", user.Profile.LastName);
                mailText = mailText.Replace("<##Phone##>", user.Profile.PhoneNumber);
                mailText = mailText.Replace("<##PersonalEmailAddress##>", user.Profile.EmailAddress);
                mailText = mailText.Replace("<##LoginEmailAddress##>", user.UserName);
                mailText = mailText.Replace("<##LoginPasswords##>", user.Password);
                mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                mailText = mailText.Replace("<##LoginPage##>", SiteSettings.SiteBaseUrl + "login.aspx");

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", user.Profile.FullName);
                items.Add("ReceiverEmail", user.Profile.EmailAddress);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                return true;
            }
            else
            {
                return false;
            }

        }

        public bool SendRegistrationEmailToAdmin(User user)
        {
            MailSettings mailSettings = new MailSettings();
            mailSettings.ServerAddress = SiteSettings.EmailServer;
            mailSettings.Port = SiteSettings.EmailPort;
            mailSettings.UserName = SiteSettings.EmailUserName;
            mailSettings.Password = SiteSettings.EmailPassword;
            mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
            mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
            mailSettings.SenderName = SiteSettings.CompanyName;

            string mailText = string.Empty;
            string mailSubject = SiteSettings.CompanyName + " :  New  Registration";
            mailText = GetTemplate(_registrationEmailAdminTemplateFilePath);
            if (!string.IsNullOrEmpty(mailText))
            {
                mailText = mailText.Replace("<##FirstName##>", user.Profile.FirstName);
                mailText = mailText.Replace("<##LastName##>", user.Profile.LastName);
                //mailText = mailText.Replace("<##Address1##>", user.Profile.DefaultAddress.AddressLine1);
                //mailText = mailText.Replace("<##Address2##>", user.Profile.DefaultAddress.AddressLine2);
                //mailText = mailText.Replace("<##City##>", user.Profile.DefaultAddress.City);
                //mailText = mailText.Replace("<##State##>", user.Profile.DefaultAddress.State);
                //mailText = mailText.Replace("<##Country##>", user.Profile.DefaultAddress.Country);
                //mailText = mailText.Replace("<##Zip##>", user.Profile.DefaultAddress.Zip);
                mailText = mailText.Replace("<##Phone##>", user.Profile.PhoneNumber);
                mailText = mailText.Replace("<##PersonalEmailAddress##>", user.Profile.EmailAddress);
                mailText = mailText.Replace("<##LoginEmailAddress##>", user.UserName);
                mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", SiteSettings.SiteName);
                items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                return true;
            }
            else
            {
                return false;
            }

            return false;
        }

        public bool SendPasswordRecoverEmail(User user)
        {
            MailSettings mailSettings = new MailSettings();
            mailSettings.ServerAddress = SiteSettings.EmailServer;
            mailSettings.Port = SiteSettings.EmailPort;
            mailSettings.UserName = SiteSettings.EmailUserName;
            mailSettings.Password = SiteSettings.EmailPassword;
            mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
            mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
            mailSettings.SenderName = SiteSettings.CompanyName;
            string mailText = string.Empty;
            string mailSubject = SiteSettings.CompanyName + " :  Your Password";

            mailText = GetTemplate(_passwordRecoveryEmailTemplateFilePath);
            if (!string.IsNullOrEmpty(mailText))
            {
                mailText = mailText.Replace("<##FirstName##>", user.Profile.FirstName);
                mailText = mailText.Replace("<##LoginEmailAddress##>", user.UserName);
                mailText = mailText.Replace("<##LoginPasswords##>", user.Password);
                mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                mailText = mailText.Replace("<##LoginPage##>", SiteSettings.SiteBaseUrl + "login.aspx");

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", user.Profile.FullName);
                items.Add("ReceiverEmail", user.Profile.EmailAddress);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                return true;
            }
            else
            {
                return false;
            }
        }

        private string GenerateInvoiceEmailBody(Order order)
        {
            string templateContent = GetTemplate(_invoiceEmailTemplateFilePath);
            if (!string.IsNullOrEmpty(templateContent))
            {
                string val = string.Empty;
                templateContent = templateContent.Replace("<##OrderNumber##>", order.OrderNumber+order.OrderId.ToString());
                templateContent = templateContent.Replace("<##ReceiptDate##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(order.OrderDate));
                templateContent = templateContent.Replace("<##ShippingName##>", order.ShippingAddress.Name);
                templateContent = templateContent.Replace("<##ShippingAddressLine1##>", order.ShippingAddress.AddressLine1);
                templateContent = templateContent.Replace("<##ShippingAddressLine2##>", order.ShippingAddress.AddressLine2);
                templateContent = templateContent.Replace("<##ShippingCity##>", order.ShippingAddress.City);
                templateContent = templateContent.Replace("<##ShippingState##>", order.ShippingAddress.State);
                templateContent = templateContent.Replace("<##ShippingZip##>", order.ShippingAddress.Zip);
                templateContent = templateContent.Replace("<##ShippingCountry##>", order.ShippingAddress.Country);

                templateContent = templateContent.Replace("<##Subtotal##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.SubTotal));
                templateContent = templateContent.Replace("<##ShippingCost##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ShippingCost));
                templateContent = templateContent.Replace("<##TotalAmount##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.TotalAmount));

                templateContent = templateContent.Replace("<##TermsAndConditionsPage##>", SiteSettings.SiteBaseUrl + "terms-and-conditions.aspx");
                templateContent = templateContent.Replace("<##SupportPage##>", SiteSettings.SiteBaseUrl + "contact-us.aspx");
                templateContent = templateContent.Replace("<##AccountInformationPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                templateContent = templateContent.Replace("<##PurchaseHistoryPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                templateContent = templateContent.Replace("<##PrivacyPolicyPage##>", SiteSettings.SiteBaseUrl + "privacy-policy.aspx");

                templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);

                templateContent = templateContent.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);

                templateContent = templateContent.Replace("<##SiteName##>", SiteSettings.SiteName);

                val = order.PaymentType.ToString();

                templateContent = templateContent.Replace("<##PaymentType##>", val);

                if (order.OrderStatus == OrderStatusType.CCSuccess && order.PaymentType == PaymentType.CreditCard)
                {
                    val="Success";
                    templateContent = templateContent.Replace("<##Color##>", "Green");
                }
                else if (order.OrderStatus == OrderStatusType.CCFail && order.PaymentType == PaymentType.CreditCard)
                {
                    val = "Failed";
                    templateContent = templateContent.Replace("<##Color##>", "Red");
                }
                else if (order.OrderStatus == OrderStatusType.ManualAuthorization && order.PaymentType == PaymentType.bKash)
                {
                    val = "Pending payment varification";
                    templateContent = templateContent.Replace("<##Color##>", "Green");
                }
                
                templateContent = templateContent.Replace("<##OrderStatus##>", val);
                
                string orderItems = string.Empty;
                foreach (OrderItem item in order.OrderItems)
                {
                    string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                        + item.ProductCode + "</td><td style=\"text-align: left\">"
                        + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                    + item.ProductName + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" /> <td style=\"height: 30px; text-align: left;\">"
                        + item.Quantity + "</td>"
                    + "</td><td style=\"text-align: left; padding-left:10px;\">" +
                    ECommerce.Library.ECommerce.Utility.FormatPriceText(item.UnitPrice) + "</td> <td style=\"height: 30px; text-align: right;\">"
                    + ECommerce.Library.ECommerce.Utility.FormatPriceText(item.TotalPrice) + "</td></tr>";
                    orderItems += temp;
                }
                templateContent = templateContent.Replace("<##OrderItems##>", orderItems);


                templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                return templateContent;
            }

            return string.Empty;
        }

        public bool SendInvoiceEmail(Order order, int userId)
        {
            try
            {
                UserProfile userProfile = UserManager.GetUserProfileByUserId(userId);
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailText = GenerateInvoiceEmailBody(order);
                string mailSubject = SiteSettings.CompanyName + " :  Receipt for Order Number " + order.OrderNumber;

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", userProfile.FullName);
                items.Add("ReceiverEmail", userProfile.EmailAddress);
                items.Add("Subject", mailSubject);

                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                items.Clear();

                items.Add("ReceiverName", "Administrator");
                items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool SendStockAlertEmailToAdmin(StockAlert alert)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  Stock Alert";
                mailText = GetTemplate(_stockAlertEmailAdminTemplateFilePath);
                if (!string.IsNullOrEmpty(mailText))
                {
                    mailText = mailText.Replace("<##ItemNumber##>", alert.ProductItemNumber);
                    mailText = mailText.Replace("<##ProductName##>", alert.ProductName);
                    mailText = mailText.Replace("<##ProductSize##>", alert.ProductSize);
                    mailText = mailText.Replace("<##StockAmount##>", alert.StockAmount.ToString());
                    mailText = mailText.Replace("<##Date##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(DateTime.Now));
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", SiteSettings.SiteName);
                    items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string PreviewNewsletterEmail(Newsletter newsletter)
        {
            try
            {
                return newsletter.Body;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public bool SendInqueryEmailToAdmin(Inquires inquiry)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  New  Inquery";
                mailText = GetTemplate(_inqueryEmailAdminTemplateFilePath);
                if (!string.IsNullOrEmpty(mailText))
                {
                    mailText = mailText.Replace("<##Name##>", inquiry.Name);
                    mailText = mailText.Replace("<##Organization##>", inquiry.Organization);
                    mailText = mailText.Replace("<##EmailAddress##>", inquiry.EmailAddress);
                    mailText = mailText.Replace("<##Telephone##>", inquiry.Telephone);
                    mailText = mailText.Replace("<##Subject##>", inquiry.Subject);
                    mailText = mailText.Replace("<##Website##>", inquiry.Website);
                    mailText = mailText.Replace("<##Inquiry##>", inquiry.Inquiry);
                    mailText = mailText.Replace("<##Date##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(inquiry.CreateDate));
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", TblSettings.GetTblSettingsBySettingsId(1).CompanyName.ToString());
                    items.Add("ReceiverEmail", TblSettings.GetTblSettingsBySettingsId(1).CompanyEmail.ToString());
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region _INACTIVE_FUNCTION

        public bool SendNewsletterEmail(Newsletter newsletter, out string fullEmailText)
        {
            try
            {
                fullEmailText = string.Empty;

                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailSubject = "E-Shop:  Newsletter";

                string mailText = newsletter.Body;

                foreach (NewsletterSubscriber subscriber in newsletter.Subscribers)
                {
                    NameValueCollection items = new NameValueCollection();
                    if (string.IsNullOrEmpty(subscriber.SubscriberName))
                        subscriber.SubscriberName = "Subscriber";
                    items.Add("ReceiverName", subscriber.SubscriberName);
                    items.Add("ReceiverEmail", subscriber.Email);
                    items.Add("Subject", mailSubject);
                    mailText = mailText + @"<br/><a href='" + SiteSettings.SiteBaseUrl + "unsubscribe.aspx" + "'>unscbscribe</a>";
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);

                }
                fullEmailText = mailText;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
    }
}
